//
//  FavHomeViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/5/19.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit

private let albumTableCellIdentirier = "FavListCell"
private let audioTableCellIdentifier = "AudioTableCell"
private let favAudioOpCellIdentifier = "FavAudioOpCell"
private let noDataCellIdentifier = "NoDataTableCell"

class FavHomeViewController: BaseViewController {

  enum FavType {
    case album, audio
  }
  
  // MARK: - IBOutlets
  
  @IBOutlet private weak var categoryContainer: UIView!
  @IBOutlet private weak var albumButton: UIButton!
  @IBOutlet private weak var audioButton: UIButton!
  @IBOutlet private weak var focusLine: UIView!
  @IBOutlet private weak var focusLineLeftConstraint: NSLayoutConstraint!
  @IBOutlet private weak var tableView: UITableView!
  
  // MARK: - Private vars
  
  private var favType: FavType = .album
  private var favAlbums = FavAlbum.getAll()
  private var favAudios = FavAudio.getAll()
  
  private var selectedAlbum: Album?
  
  // MARK: - Private methods
  
  private func prepareUI() {
    tableView.register(UINib(nibName: audioTableCellIdentifier, bundle: nil), forCellReuseIdentifier: audioTableCellIdentifier)
    tableView.register(UINib(nibName: noDataCellIdentifier, bundle: nil), forCellReuseIdentifier: noDataCellIdentifier)
  }
  
  private func focus(type: FavType) {
    if type != favType {
      favType = type
      UIView.animate(withDuration: 0.3) {
        switch type {
        case .album:
          self.albumButton.isSelected = true
          self.audioButton.isSelected = false
          self.focusLineLeftConstraint.constant = 0
        case .audio:
          self.albumButton.isSelected = false
          self.audioButton.isSelected = true
          self.focusLineLeftConstraint.constant = self.categoryContainer.width / 2
        }
        self.view.layoutIfNeeded()
      }
      tableView.reloadData()
    }
  }
  
  // MARK: - Public vars
  
  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    prepareUI()
  }
  
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    favAlbums = FavAlbum.getAll()
    favAudios = FavAudio.getAll()
    tableView.reloadData()
  }
  
  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "ShowAlbumDetailSegue" {
      let albumDetailViewController = segue.destination as! AlbumDetailViewController
      albumDetailViewController.albumIdentifier = Int(selectedAlbum!.id)
    } else if segue.identifier == "ShowAddToPlayListFromFavAudioSegue" {
      let nav = segue.destination as! BaseNavigationController
      nav.dismissDelegate = self
      let addToPlayListStep1ViewController = nav.viewControllers.first as! AddToPlayListStep1ViewController
      
      var audios = [Audio]()
      favAudios?.forEach {
        if let audio = EntityManager.fetch(Audio.self, fetchType: .id(Int($0.audioID)))?.first {
          audios.append(audio)
        }
      }
      addToPlayListStep1ViewController.audios = audios
    }
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  // MARK: - IBActions
  
  @IBAction func changeTypeToAlbum() {
    focus(type: .album)
  }
  
  @IBAction func changeTypeToAudio() {
    focus(type: .audio)
  }
  
  // MARK: - Public methods
  
  
}

// MARK: - UITableViewDataSource

extension FavHomeViewController: UITableViewDataSource {
  func numberOfSections(in tableView: UITableView) -> Int {
    switch favType {
    case .album:
      return 1
    case .audio:
      if let count = favAudios?.count, count > 0 {
        return 2
      } else {
        return 1
      }
    }
  }
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    switch favType {
    case .album:
      if let count = favAlbums?.count, count > 0 {
        return count
      } else {
        return 1
      }

    case .audio:
      if let count = favAudios?.count, count > 0 {
        if section == 0 {
          return 1
        } else {
          return count
        }
      } else {
        return 1
      }
    }
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    switch favType {
    case .album:
      if let count = favAlbums?.count, count > 0 {
        // fav cell
        let cell = tableView.dequeueReusableCell(withIdentifier: albumTableCellIdentirier, for: indexPath) as! FavListCell
        if let albumID = favAlbums?[indexPath.row].albumID,
          let album = EntityManager.fetch(Album.self, fetchType: .id(Int(albumID)))?.first {
          
          cell.prepare(album: album)
        }
        return cell
      } else {
        // no data cell
        let cell = tableView.dequeueReusableCell(withIdentifier: noDataCellIdentifier, for: indexPath) as! NoDataTableCell
        cell.tipLabel.text = "没有收藏节目"
        return cell
      }
      
    case .audio:
      if let count = favAudios?.count, count > 0 {
        if indexPath.section == 0 {
          // op cell
          let cell = tableView.dequeueReusableCell(withIdentifier: favAudioOpCellIdentifier, for: indexPath) as! FavAudioOpCell
          cell.delegate = self
          return cell
        } else {
          // fav cell
          let cell = tableView.dequeueReusableCell(withIdentifier: audioTableCellIdentifier, for: indexPath) as! AudioTableCell
          if let audioID = favAudios?[indexPath.row].audioID,
            let audio = EntityManager.fetch(Audio.self, fetchType: .id(Int(audioID)))?.first {
            
            cell.prepare(audio: audio)
          }
          return cell
        }
      } else {
        // no data cell
        let cell = tableView.dequeueReusableCell(withIdentifier: noDataCellIdentifier, for: indexPath) as! NoDataTableCell
        cell.tipLabel.text = "没有收藏声音"
        return cell
      }
    }
  }
}

// MARK: - UITableViewDelegate

extension FavHomeViewController: UITableViewDelegate {
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    switch favType {
    case .album:
      if let count = favAlbums?.count, count > 0,
        let albumID = favAlbums?[indexPath.row].albumID,
        let album = EntityManager.fetch(Album.self, fetchType: .id(Int(albumID)))?.first {
        
        selectedAlbum = album
        performSegue(withIdentifier: "ShowAlbumDetailSegue", sender: nil)
      } else {
        selectedAlbum = nil
      }
      
    case .audio:
      if let count = favAudios?.count, count > 0,
        let audioID = favAudios?[indexPath.row].audioID,
        let audio = EntityManager.fetch(Audio.self, fetchType: .id(Int(audioID)))?.first,
        let album = audio.album {
        
        var audios = [Audio]()
        favAudios?.forEach {
          if let audio = EntityManager.fetch(Audio.self, fetchType: .id(Int($0.audioID)))?.first {
            audios.append(audio)
          }
        }
        NowPlayingManager.shared.update (
          audioList: audios,
          audioListName: "收藏",
          audioLsitType: .fav,
          audioListRefID: nil
        )
        NowPlayingManager.shared.play(album: album, audio: audio)
      }
    }
    tableView.deselectRow(at: indexPath, animated: true)
  }
  
  func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    switch favType {
    case .album:
      if let count = favAlbums?.count, count > 0 {
        return true
      } else {
        return false
      }
    case .audio:
      if let count = favAudios?.count, count > 0 {
        if indexPath.section == 0 {
          return false
        } else {
          return true
        }
      } else {
        return false
      }
    }
  }
  
  func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
      switch favType {
      case .album:
        if let favAlbum = favAlbums?[indexPath.row] {
          do {
            try FavAlbum.remove(favAlbum)
            favAlbums?.remove(at: indexPath.row)
            if let count = favAlbums?.count, count > 0 {
              tableView.deleteRows(at: [indexPath], with: .automatic)
            } else {
              tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .automatic)
            }
          } catch { }
        }
        
      case .audio:
        if let favAudio = favAudios?[indexPath.row] {
          do {
            try FavAudio.remove(favAudio)
            favAudios?.remove(at: indexPath.row)
            if let count = favAudios?.count, count > 0 {
              tableView.deleteRows(at: [indexPath], with: .automatic)
            } else {
              tableView.reloadData()
            }
          } catch { }
        }
      }
    }
  }
  
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    switch favType {
    case .album:
      if let count = favAlbums?.count, count > 0 {
        return FavListCell.defaultHeight
      } else {
        return NoDataTableCell.defaultHeight
      }
    case .audio:
      if let count = favAudios?.count, count > 0 {
        if indexPath.section == 0 {
          return FavAudioOpCell.defaultHeight
        } else {
          return AudioTableCell.defaultHeight
        }
      } else {
        return NoDataTableCell.defaultHeight
      }
    }
  }
}

// MARK: - DownloadOpCellDelegate

extension FavHomeViewController: FavAudioOpCellDelegate {
  func addToPlaylist() {
    if UserManager.shared.currentUser != nil {
      performSegue(withIdentifier: "ShowAddToPlayListFromFavAudioSegue", sender: nil)
    }
  }
}

// MARK: - BaseNavigationControllerDismissDelegate

extension FavHomeViewController: BaseNavigationControllerDismissDelegate {
  func dismiss(navigationController: BaseNavigationController, completion: (() -> Void)?) {
    dismiss(animated: true, completion: completion)
  }
}
